package com.zxy.zxyrpc.protocol;

import com.zxy.zxyrpc.exception.RpcException;
import com.zxy.zxyrpc.model.ErrorCode;
import com.zxy.zxyrpc.serializer.Serializer;
import com.zxy.zxyrpc.serializer.SerializerFactory;
import io.vertx.core.buffer.Buffer;

import java.io.IOException;

/**
 * 协议消息编码器
 *
 * @author zxy
 * @since 2025/5/22
 **/
public class ProtocolMessageEncoder {
    /**
     * 编码
     *
     * @param protocolMessage 协议消息
     */
    public static Buffer encode(ProtocolMessage<?> protocolMessage) throws IOException {
        Buffer buffer = Buffer.buffer();
        if (protocolMessage == null || protocolMessage.getHeader() == null)
            return buffer;
        ProtocolMessage.Header header = protocolMessage.getHeader();
        // 消息头组装
        buffer.appendByte(header.getMagic());
        buffer.appendByte(header.getVersion());
        buffer.appendByte(header.getSerializer());
        buffer.appendByte(header.getType());
        buffer.appendByte(header.getStatus());
        buffer.appendLong(header.getRequestId());

        // 消息体序列化
        ProtocolMessageSerializerEnum serializerEnum = ProtocolMessageSerializerEnum.getEnumByKey(header.getSerializer());
        if (serializerEnum == null)
            throw new RpcException(ErrorCode.NOT_FOUND_ERROR, "序列化协议不存在");
        Serializer serializer = SerializerFactory.getInstance(serializerEnum.getValue());
        byte[] bodyBytes = serializer.serialize(protocolMessage.getBody());
        // 写入数据长度和数据
        buffer.appendInt(bodyBytes.length);
        buffer.appendBytes(bodyBytes);
        return buffer;
    }
}
